;(function () {
    "use strict";

    var $form_add_task = $('.add-task'),
        $task_detail_trigger,
        $task_delete_trigger,
        $task_detail = $('.task-detail'),
        $task_detail_mask = $('.task-detail-mask'),
        current_index,
        $update_form,
        $task_detail_content,
        $task_detail_content_input,
        $checkbox_complete,
        $msg=$('.msg'),
        $msg_content=$msg.find('.msg-content'),
        $msg_confirm=$msg.find('.confirmed'),
        $alerter=$('.alerter'),
        task_list = [];


    init();

    /*添加任务触发submit*/
    $form_add_task.on('submit', on_add_task_form_submit);
    /*点击遮幕显示详情与遮幕*/
    $task_detail_mask.on('click', hide_task_detail);

    function listen_msg_event() {
        $msg_confirm.on('click',function () {
            hide_msg();
        });
    }

    /*添加任务*/
    function on_add_task_form_submit(e) {
        var new_task = {}, $input;
        e.preventDefault();
        /*获取新task值*/
        $input = $(this).find('input[name=content]');
        new_task.content = $input.val();
        /*新的task值为空，则直接返回*/
        if (!new_task.content) return;
        if (add_task(new_task)) {
            $input.val(null);
        }
    }

    /*点击详情获取详情面板*/
    function Listen_task_detail() {
        var index;
        $('.task-item').on('dblclick', function () {
            index = $(this).data('index');
            show_task_detail(index);
        });
        $task_detail_trigger.on('click', function () {
            var $this = $(this);
            var $item = $this.parent().parent();
            var index = $item.data('index');
            show_task_detail(index);
        })
    }

    /*监听完成任务事件*/
    function Listen_checkbox_complete() {
        $checkbox_complete.on('click', function () {
            var $this = $(this);
            var index = $this.parent().parent().data('index');
            var item = get(index);
            if (item.complete)
                update_task(index, {complete: false});
            else
                update_task(index, {complete: true});
        })
    }

    function get(index) {
        return store.get('task_list')[index];
    }

    /*显示详情与遮幕---查看task详情*/
    function show_task_detail(index) {
        render_task_detail(index);
        current_index = index;
        $task_detail.show();
        $task_detail_mask.show();
    }

    function update_task(index, data) {
        if (!index || !task_list[index])  return;
        task_list[index] = $.extend({}, task_list[index], data);
        refresh_task_list();
    }

    /*隐藏详情与遮幕*/
    function hide_task_detail() {
        $task_detail.hide();
        $task_detail_mask.hide();
    }

    /*渲染指定task的详细信息*/
    function render_task_detail(index) {
        if (index === undefined || !task_list[index]) return;
        var item = task_list[index];
        var tpl = '<form>' +
            '<div class="content">' + item.content + '</div>' +
            '<div class="input_item">' +
            '<input style="display: none" type="text" name="content" value="' + (item.content || '') + '">' +
            '</div>' +
            '<div>' +
            '<div class="desc input_item">' +
            '<textarea name="desc">' + (item.desc || '') + '</textarea>' +
            '</div>' +
            '</div>' +
            '<div class="remind input_item">' +
            '<label>提醒时间</label>'+
            '<input class="datetime" type="text" name="remind_date" value="' + (item.remind_date || '') + '" >' +
            '</div>' +
            '<div class="input_item">' +
            '<button type="submit">更新</button>' +
            '</div>' +
            '</form>';
        $task_detail.html('');
        $task_detail.html(tpl);
        $('.datetime').datetimepicker();
        $update_form = $task_detail.find('form');
        $task_detail_content = $update_form.find('.content');
        $task_detail_content_input = $update_form.find('[name=content]');
        /*双击内容元素显示input, 隐藏自己*/
        $task_detail_content.on('dblclick', function () {
            $task_detail_content.hide();
            $task_detail_content_input.show();
        });

        $update_form.on('submit', function (e) {
            e.preventDefault();
            var data = {};
            data.content = $(this).find('[name = content]').val();
            data.desc = $(this).find('[name = desc]').val();
            data.remind_date = $(this).find('[name = remind_date]').val();
            update_task(index, data);
            hide_task_detail();
        })
    }

    /*删除task—item的某一项*/
    function Listen_task_delete() {
        $task_delete_trigger.on('click', function () {
            var $this = $(this);
            var $item = $this.parent().parent();
            var index = $item.data('index');
            /*确认删除*/
            var tmp = confirm('确定要删除么？');
            tmp ? delete_task(index) : null;
        })
    }

    /*add_task*/
    function add_task(new_task) {
        /*吧task用push方法到task_list，并更新localStorage*/
        task_list.push(new_task);
        refresh_task_list();
        return true;
    }

    /*刷新localStorage,并更新渲染模板*/
    function refresh_task_list() {
        store.set('task_list', task_list);
        render_task_list();
    }

    /*删除task_list中某项内容*/
    function delete_task(index) {
        if (index == undefined || !task_list[index]) return;
        delete task_list[index];
        refresh_task_list();
    }


    function init() {
        task_list = store.get('task_list') || [];
        listen_msg_event();
        if (task_list.length)
            render_task_list();
        task_remind_check();

    }

    /*提醒功能*/
    function task_remind_check() {
        var current_timestamp;
        /*定时器*/
        var itl = setInterval(function () {
            for (var i = 0; i < task_list.length; i++) {
                var item = get(i), task_timestamp;
                if (!item || !item.remind_date || item.informed)  continue;
                current_timestamp = (new Date()).getTime();
                task_timestamp = (new Date(item.remind_date)).getTime();
                if (current_timestamp - task_timestamp >= 1) {
                    update_task(i, {informed: true});
                    show_msg(item.content);
                }
            }
        }, 500);
    }

    function show_msg(msg) {
        if(!msg) return;
        $alerter.get(0).play();
        $msg_content.html(msg);
        $msg.show();
    }
    function hide_msg() {
        $msg.hide();
    }

    /*把task_list_tpl模板逐一添加或者删除到task_list中*/
    function render_task_list() {
        var $task_list = $('.task_list');
        $task_list.html('');
        var complete_items = [];
        for (var i = 0; i < task_list.length; i++) {
            var item = task_list[i];
            if (item && item.complete)
                complete_items[i] = item;
            else
                var $task = render_task_item(item, i);
            $task_list.prepend($task);
        }

        for (var j = 0; j < complete_items.length; j++) {
            $task = render_task_item(complete_items[j], j);
            if (!$task) continue;
            $task.addClass('completed');
            $task_list.append($task);
        }

        $task_delete_trigger = $('.action.delete');
        $task_detail_trigger = $('.action.detail');
        $checkbox_complete = $('.task_list .complete[type=checkbox]');
        Listen_task_delete();
        Listen_task_detail();
        Listen_checkbox_complete();
    }

    /*渲染task_list_tpl模板*/
    function render_task_item(data, index) {
        if (!data || !index) return;
        var list_item_tpl =
            '<div class="task-item" data-index="' + index + '">' +
            '<span><input class="complete " ' + (data.complete ? 'checked' : '') + ' type="checkbox"></span>' +
            '<span class="task-content">' + data.content + '</span>' +
            '<span class="fr">' +
            '<span class="action delete"> 删除</span>' +
            '<span class="action detail"> 详情</span>' +
            '</span>' +
            '</div>';
        return $(list_item_tpl);
    }
})();